const cheerio = require('cheerio');
const http = require('http');
const fs = require('fs');
const process = require('child_process');


const url = "http://www.mca.gov.cn/article/sj/xzqh/2019/201901-06/20190203221738.html";

http.get(url, (res) => {
    let chunks = [];
    let size = 0;
    
    res.on('data', (chunk) => {
        chunks.push(chunk);
        size += chunk.length;
    });

    res.on('end', () => {
        let data = Buffer.concat(chunks, size);
        let html = data.toString();

        let $ = cheerio.load(html, {
            decodeEntities: false
        });

        let res = [];

        let item = null;
        $("table").find("tr").each(function(){
            let lists = $(this).find(".xl704140");
            
            if (lists.length == 2) {
                // 真实数据行
                let code = lists.eq(0).html();
                let name = lists.eq(1).html();                

                if (code.length > 0 && name.length > 0) {
                    // 省 (直辖市)
                    if (Number.isInteger(code / 10000)) {
                        if (item) {
                            res.push(item);
                        }

                        item = {
                            state: {
                                code: code,
                                name: name
                            },
                            cities: []
                        };  
                    } else {
                        item.cities.push({
                            code: code,
                            name: name
                        });
                    }
                }
            }
        });

        let jsonStr = JSON.stringify(res);

        fs.writeFile('./city.json', jsonStr, (err) => {
            if (err) {
                console.log("写入文件失败:", err);        
            } else {
                console.log("写入成功");
                
                // 生成plist
                process.exec("plutil -convert xml1 city.json -o city.plist", (err) => {
                    if (err) {
                        console.log("转换plist失败");
                    } else {
                        console.log("生成plist完成");
                    }
                });
            }
        });
        
    });
});
